package com.test.demo.io.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.*;

public class NIOSelectorSocketServer {

    private static List<SocketChannel> list=new ArrayList<>();
    public static void main(String[] args) throws IOException {
        //创建NIOSocketChannel
        ServerSocketChannel socketChannel = ServerSocketChannel.open();
        socketChannel.bind(new InetSocketAddress(9000));
        //等待连接的时候设置非阻塞
        socketChannel.configureBlocking(false);
        //创建多路复用器，就是Epoll
        Selector selector = Selector.open();
        socketChannel.register(selector, SelectionKey.OP_ACCEPT);
        System.out.println("NIOSocketServer 启动了");

        while (true){
            //等待事件的发生
            selector.select();

            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator1 = selectionKeys.iterator();

            while (iterator1.hasNext()){
                SelectionKey selectionKey = iterator1.next();

                if (selectionKey.isAcceptable()){
                    //新的客户端注册
                    ServerSocketChannel sc = (ServerSocketChannel)selectionKey.channel();
                    SocketChannel accept = sc.accept();
                    accept.configureBlocking(false);
                    //绑定selector,注册读事件
                    accept.register(selector,SelectionKey.OP_READ);
                }else if (selectionKey.isReadable()){
                    SocketChannel sc = (SocketChannel)selectionKey.channel();

                    ByteBuffer byteBuffer = ByteBuffer.allocate(128);
                    int read = sc.read(byteBuffer);
                    if (read>0){
                        System.out.println("收到客户端数据"+new String(byteBuffer.array()));
                    }else if (read==-1){
                        System.out.println("客户端关闭了");
                    }
                }
                iterator1.remove();
            }

        }
    }
}
